import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Dept } from "./dept.entity";
import { FindOptionsWhere, Repository } from "typeorm";
import { System } from "src/system/system.entity";
import { DeptRoleEnum, RoleEnum } from "src/role/role.enum";
import { UserSys } from "src/user/userSys.entity";
import { UserService } from "src/user/user.service";



@Injectable()
export class DeptService {
    constructor(
        @InjectRepository(Dept)
        public readonly dept: Repository<Dept>,
        private readonly userService: UserService
    ) { }
    async find(where?: FindOptionsWhere<Dept>, relations = ["parent"]) {
        return await this.dept.find({
            where,
            relations
        })
    }

    async getParentResponsibility(user: UserSys) {
        //项目经理、特殊部门 获得总经理
        if (user.role === RoleEnum.manager || user.dept?.deptRole !== DeptRoleEnum.member) {
            return this.userService.findsBy({
                system: {
                    id: user.system.id
                },
                role: RoleEnum.director
            })
        }
        //员工获得项目经理
        if (user.role === RoleEnum.member) {
            return this.userService.findsBy({
                system: {
                    id: user.system.id
                },
                role: RoleEnum.manager,
                dept: { id: user.dept.id }
            })
        }
    }


    async create(
        name: string,
        system: System,
        editable = true,
        deptRole = DeptRoleEnum.member,
        parent?: Dept
    ) {
        const entity = this.dept.create({
            name,
            editable,
            parent,
            deptRole,
            system
        });
        return await this.dept.save(entity)
    }
    async getDirector(user: UserSys) {
        const manager = await this.userService.findsBy({
            system: {
                id: user.system.id
            },
            role: RoleEnum.director,

        })
        return manager
    }

    async depinfo(user: UserSys) {
        const manager = await this.getDirector(user);
        const users = await this.userService.findsBy({
            system: {
                id: user.system.id
            }
        })
    }

    async userdeptinfo(user: UserSys) {
        const manager = await this.userService.findsBy({
            system: {
                id: user.system.id
            },
            dept: {
                id: user.dept.id
            },
            role: RoleEnum.manager
        })
        return manager
    }



}